#include "x11clenteventfilter.h"

X11ClentEventFilter::X11ClentEventFilter(QObject *parent) : QThread(parent)
  ,m_display(XOpenDisplay(nullptr))
  ,m_rootwin(DefaultRootWindow(m_display))
{

}

void X11ClentEventFilter::run()
{
    qDebug() << Q_FUNC_INFO << "RootWin: " << m_rootwin;
    XSelectInput( m_display, m_rootwin, SubstructureNotifyMask);/*事件可以参考x.h*/
    XEvent event;

    while ( 1 )
    {
        XNextEvent(m_display, &event );
        qDebug() << Q_FUNC_INFO << "event: " << event.type;
        if ( event.type == ReparentNotify )
        {
            qDebug() << "ReparentNotify.";
            Window x11window;
            Display *x11display;
            char **srname = (char **)malloc(sizeof(char *));
            XReparentEvent *reparentevent = (XReparentEvent *)&event;

            qDebug() << Q_FUNC_INFO << "window: " << reparentevent->window;
            qDebug() << Q_FUNC_INFO << "parent: " << reparentevent->parent;
            /*获取到新建窗口的window ID*/
            x11window = (unsigned long)(reparentevent->window);
            x11display =(reparentevent->display);
            XFetchName(x11display, x11window, srname);
            x11display = XOpenDisplay(nullptr);/*！！！注意这里以后如果你想对获取到的window ID进行操作必须重新链接*/

            if(*srname != nullptr)
                qDebug() << Q_FUNC_INFO << *srname;

            free(*srname);
        }
        else if(event.type == ConfigureNotify)
        {
            QRect rect;
            XConfigureEvent *configureevent = (XConfigureEvent *)&event;
            rect.setX(configureevent->x);
            rect.setY(configureevent->y);
            rect.setWidth(configureevent->width);
            rect.setHeight(configureevent->height);
            emit clientResize(configureevent->window, rect);
        }
    }

}
